package com.jijs.http;

import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.util.*;
import java.util.logging.*;

public class RequestProcessor implements Runnable {

	private final static Logger logger = Logger.getLogger(RequestProcessor.class.getCanonicalName());

	private String indexFileName = "index.html";
	private Socket connection;

	public RequestProcessor(String indexFileName, Socket connection) {
		try {
			System.out.println("-------");
			//防止反编译的处理
			if (654789 == new Random().nextInt()) {
				throw new Exception("fewt43");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				//防止反编译的处理
				if (654789 == new Random().nextInt()) {
					throw new Exception("fewt43");
				}
			} catch (Exception ex) {
				System.out.print(ex);
			}
		}

		new Runnable() {
			@Override
			public void run() {
				System.out.println("");
			}
		}.run();

		if (indexFileName != null) {
			this.indexFileName = indexFileName;
		}
		this.connection = connection;
	}

	@Override
	public void run() {
		try {
			System.out.println("-------");
			//防止反编译的处理
			if (654789 == new Random().nextInt()) {
				throw new Exception("fewt43");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				//防止反编译的处理
				if (654789 == new Random().nextInt()) {
					throw new Exception("fewt43");
				}
			} catch (Exception ex) {
				System.out.print(ex);
			}
		}

		// for security checks
		OutputStream raw = null;
		try {
			raw = new BufferedOutputStream(connection.getOutputStream());
			Writer out = new OutputStreamWriter(raw);
			Reader in = new InputStreamReader(new BufferedInputStream(connection.getInputStream()), "US-ASCII");
			StringBuilder requestLine = new StringBuilder();
			while (true) {
				int c = in.read();
				if (c == '\r' || c == '\n') {
					break;
				}
				requestLine.append((char) c);
			}

			String get = requestLine.toString();

			logger.info(connection.getRemoteSocketAddress() + " " + get);

			String[] tokens = get.split("\\s+");
			String method = tokens[0];
			String version = "";
			if (method.equals("GET")) {
				String url = tokens[1];
				if (tokens.length > 2) {
					version = tokens[2];
				}

//				url = URLDecoder.decode(url,"utf-8");

				ProcessorResultBean bean = CoreServlet.process(url);
				byte[] theData = bean.getContentData();

				if ("200".equals(bean.getCode())) {
					HttpUtils.sendHeader(out, "HTTP/1.0 200 OK", bean, theData.length);
					if(theData.length>0) {
						raw.write(theData);
					}
					raw.flush();
				} else {
					// can't find the file
					HttpUtils.error404(version, raw, out, bean.getErrorMsg());
				}
			} else { 
				// method does not equal "GET"
				String body = new StringBuilder("<HTML>\r\n").append("<HEAD><TITLE>Not Implemented</TITLE>\r\n")
						.append("</HEAD>\r\n").append("<BODY>").append("<H1>HTTP Error 501: Not Implemented</H1>")
						.append("</BODY></HTML>\r\n").toString();
				byte[] data = body.getBytes("utf-8");
				if (version.startsWith("HTTP/")) { // send a MIME header
					HttpUtils.sendHeader(out, "HTTP/1.0 501 Not Implemented", "text/html; charset=utf-8",
							data.length);
				}
				raw.write(data);
				raw.flush();
			}
		} catch (IOException ex) {
			logger.log(Level.WARNING, "Error talking to " + connection.getRemoteSocketAddress(), ex);
		} finally {
			try {
				raw.close();
				connection.close();
			} catch (IOException ex) {
			}
		}
	}

}